import { computed, inject, isRef, ref, unref } from 'vue'
import { get } from 'lodash-unified'
import English from '@/locale/lang/en'

export const buildTranslator =
  (locale) =>
  (path, option) =>
    translate(path, option, unref(locale))

export const translate = (
  path,
  option ,
  locale
) =>
  get(locale, path, path).replace(
    /\{(\w+)\}/g,
    (_, key) => `${option?.[key] ?? `{${key}}`}`
  )

export const buildLocaleContext = (locale
) => {
  const lang = computed(() => unref(locale).name)
  const localeRef = isRef(locale) ? locale : ref(locale)
  return {
    lang,
    locale: localeRef,
    t: buildTranslator(locale),
  }
}

export const localeContextKey =
  Symbol('localeContextKey')

export const useLocale = (localeOverrides) => {
  const locale = localeOverrides || inject(localeContextKey, ref())!
  return buildLocaleContext(computed(() => locale.value || English))
}
